<template>
    <div class="repair-container">
      <!-- 顶部搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索师傅或服务类型"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="searchMasters">搜索</el-button>
      </div>
  
      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧分类导航 -->
        <div class="category-sidebar">
          <el-menu
            :default-active="activeCategory"
            class="category-menu"
            @select="handleCategorySelect"
          >
            <el-menu-item
              v-for="category in categories"
              :key="category.id"
              :index="category.id.toString()"
            >
              <template #title>
                <el-icon>
                  <component :is="getCategoryIcon(category.id)" />
                </el-icon>
                <span>{{ category.name }}</span>
              </template>
            </el-menu-item>
          </el-menu>
        </div>
  
        <!-- 右侧师傅列表 -->
        <div class="master-list-container">
          <div v-if="loading" class="loading-indicator">
            <el-icon class="is-loading"><Loading /></el-icon>
            加载中...
          </div>
          
          <div class="master-list">
            <el-card
              v-for="master in filteredMasters"
              :key="master.id"
              class="master-card"
              shadow="hover"
            >
              <div class="master-header">
                <div class="master-avatar">
                  <img :src="master.avatar" alt="师傅头像" />
                </div>
                <div class="master-info">
                  <h3 class="master-name">{{ master.name }}</h3>
                  <div class="master-tags">
                    <el-tag
                      v-for="tag in master.tags"
                      :key="tag"
                      size="small"
                      type="info"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <div class="master-rating">
                    <el-rate
                      v-model="master.rating"
                      disabled
                      show-score
                      text-color="#ff9900"
                      score-template="{value}分"
                    />
                  </div>
                </div>
              </div>
              
              <div class="master-details">
                <div class="detail-item">
                  <el-icon><Briefcase /></el-icon>
                  <span>服务类型: {{ master.serviceType }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Coin /></el-icon>
                  <span>收费标准: {{ master.price }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Location /></el-icon>
                  <span>服务区域: {{ master.serviceArea }}</span>
                </div>
                <div class="detail-item">
                  <el-icon><Document /></el-icon>
                  <span>接单量: {{ master.orderCount }}单</span>
                </div>
                <div class="detail-item description">
                  <el-icon><InfoFilled /></el-icon>
                  <span>个人简介: {{ master.description }}</span>
                </div>
              </div>
              
              <div class="master-actions">
                <el-button type="primary" @click="showBookingDialog(master)">
                  <el-icon><Calendar /></el-icon> 立即预约
                </el-button>
                <el-button @click="showDetail(master)">
                  <el-icon><View /></el-icon> 查看详情
                </el-button>
              </div>
            </el-card>
          </div>
          
          <!-- 分页控件 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="totalMasters"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
  
      <!-- 预约对话框 -->
      <el-dialog v-model="bookingDialogVisible" title="预约维修服务" width="50%">
        <el-form :model="bookingForm" label-width="100px">
          <el-form-item label="服务类型" required>
            <el-input v-model="bookingForm.serviceType" disabled />
          </el-form-item>
          <el-form-item label="师傅姓名" required>
            <el-input v-model="bookingForm.masterName" disabled />
          </el-form-item>
          <el-form-item label="预约时间" required>
            <el-date-picker
              v-model="bookingForm.bookingTime"
              type="datetime"
              placeholder="选择预约时间"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
            />
          </el-form-item>
          <el-form-item label="服务地址" required>
            <el-input
              v-model="bookingForm.bookingAddress"
              type="textarea"
              :rows="3"
              placeholder="请输入详细服务地址"
            />
          </el-form-item>
          <el-form-item label="问题描述" required>
            <el-input
              v-model="bookingForm.problemDescription"
              type="textarea"
              :rows="4"
              placeholder="请详细描述您的问题"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="bookingDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitBooking">确认预约</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 师傅详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="师傅详情" width="60%">
        <div v-if="currentMaster" class="master-detail">
          <div class="detail-header">
            <div class="detail-avatar">
              <img :src="currentMaster.avatar" alt="师傅头像" />
            </div>
            <div class="detail-info">
              <h2>{{ currentMaster.name }}</h2>
              <div class="detail-rating">
                <el-rate
                  v-model="currentMaster.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}分"
                />
                <span class="order-count">已接{{ currentMaster.orderCount }}单</span>
              </div>
              <div class="detail-service">
                <span>服务类型: {{ currentMaster.serviceType }}</span>
                <span>服务区域: {{ currentMaster.serviceArea }}</span>
              </div>
            </div>
          </div>
          
          <div class="detail-content">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="基本信息" name="basic">
                <div class="basic-info">
                  <div class="info-item">
                    <span class="label">年龄:</span>
                    <span class="value">{{ currentMaster.age || '未知' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">工作经验:</span>
                    <span class="value">{{ currentMaster.experience || '未知' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">联系电话:</span>
                    <span class="value">{{ currentMaster.phone || '预约后可见' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">收费标准:</span>
                    <span class="value">{{ currentMaster.price || '面议' }}</span>
                  </div>
                </div>
                <div class="description">
                  <h3>个人简介</h3>
                  <p>{{ currentMaster.description }}</p>
                </div>
              </el-tab-pane>
              
              <el-tab-pane label="服务评价" name="reviews">
                <div v-if="currentMaster.reviews && currentMaster.reviews.length > 0" class="review-list">
                  <div v-for="review in currentMaster.reviews" :key="review.id" class="review-item">
                    <div class="review-header">
                      <span class="review-user">{{ review.user }}</span>
                      <el-rate v-model="review.rating" disabled size="small" />
                      <span class="review-time">{{ review.time }}</span>
                    </div>
                    <div class="review-content">{{ review.content }}</div>
                  </div>
                </div>
                <div v-else class="no-reviews">
                  暂无评价
                </div>
              </el-tab-pane>
              
              <el-tab-pane label="服务案例" name="cases">
                <div v-if="currentMaster.cases && currentMaster.cases.length > 0" class="case-list">
                  <div v-for="(item, index) in currentMaster.cases" :key="index" class="case-item">
                    <div class="case-title">{{ item.title }}</div>
                    <div class="case-images">
                      <img
                        v-for="(img, imgIndex) in item.images"
                        :key="imgIndex"
                        :src="img"
                        @click="previewImage(img)"
                      />
                    </div>
                    <div class="case-desc">{{ item.description }}</div>
                  </div>
                </div>
                <div v-else class="no-cases">
                  暂无服务案例
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
          
          <div class="detail-actions">
            <el-button type="primary" size="large" @click="showBookingDialog(currentMaster)">
              <el-icon><Calendar /></el-icon> 立即预约
            </el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue'
  import {
    Search,
    Calendar,
    View,
    Briefcase,
    Coin,
    Location,
    Document,
    InfoFilled,
    Loading,
    User,
    Tools,
    Watermelon,
    House,
    Connection,
    Brush,
    Setting,
    ChatLineRound,
    Star
  } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  // 分类数据
  const categories = ref([
    { id: 1, name: '全部师傅' },
    { id: 2, name: '水电工' },
    { id: 3, name: '泥瓦工' },
    { id: 4, name: '油漆工' },
    { id: 5, name: '木工' },
    { id: 6, name: '日常维修' }
  ])
  
  // 获取分类图标
  const getCategoryIcon = (categoryId) => {
    const icons = {
      1: User,
      2: Watermelon,
      3: House,
      4: Brush,
      5: Connection,
      6: Tools
    }
    return icons[categoryId] || User
  }
  
  // 搜索相关
  const searchQuery = ref('')
  const activeCategory = ref('1')
  
  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(10)
  const totalMasters = ref(0)
  
  // 对话框控制
  const bookingDialogVisible = ref(false)
  const detailDialogVisible = ref(false)
  const activeTab = ref('basic')
  const currentMaster = ref(null)
  
  // 预约表单
  const bookingForm = ref({
    masterId: null,
    masterName: '',
    serviceType: '',
    bookingTime: '',
    bookingAddress: '',
    problemDescription: ''
  })
  
  // 时间选择快捷选项
  const shortcuts = [
    {
      text: '今天',
      value: new Date()
    },
    {
      text: '明天',
      value: () => {
        const date = new Date()
        date.setTime(date.getTime() + 3600 * 1000 * 24)
        return date
      }
    },
    {
      text: '一周后',
      value: () => {
        const date = new Date()
        date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
        return date
      }
    }
  ]
  
  // 禁用过去的日期
  const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7
  }
  
  // 师傅数据
  const masters = ref([])
  const loading = ref(false)
  
  // 初始化师傅数据
  const initMastersData = () => {
    loading.value = true
    // 模拟从后端获取数据
    setTimeout(() => {
      const mockMasters = []
      const serviceTypes = [
        '水电安装维修',
        '墙面地面修补',
        '家具刷漆翻新',
        '木工定制安装',
        '日常家居维修',
        '管道疏通清理'
      ]
      const names = ['张师傅', '李师傅', '王师傅', '赵师傅', '刘师傅', '陈师傅']
      const areas = ['朝阳区', '海淀区', '东城区', '西城区', '丰台区', '通州区']
      
      for (let i = 1; i <= 50; i++) {
        const categoryId = Math.floor(Math.random() * 5) + 2 // 2-6
        const rating = (Math.random() * 1 + 4).toFixed(1) // 4-5分
        const orderCount = Math.floor(Math.random() * 100) + 10
        
        mockMasters.push({
          id: i,
          name: names[Math.floor(Math.random() * names.length)] + (i % 5 === 0 ? i : ''),
          avatar: `https://randomuser.me/api/portraits/men/${i % 30}.jpg`,
          serviceType: serviceTypes[categoryId - 2],
          categoryId,
          price: `${Math.floor(Math.random() * 200) + 100}元/次`,
          serviceArea: areas[Math.floor(Math.random() * areas.length)],
          rating: parseFloat(rating),
          orderCount,
          age: Math.floor(Math.random() * 20) + 30,
          experience: `${Math.floor(Math.random() * 10) + 5}年`,
          phone: `138${Math.floor(10000000 + Math.random() * 90000000)}`,
          description: `专业${serviceTypes[categoryId - 2]}，有${Math.floor(Math.random() * 10) + 5}年从业经验，服务周到，价格合理。`,
          tags: ['经验丰富', '价格合理', '服务周到', '准时上门'].slice(0, Math.floor(Math.random() * 3) + 1),
          reviews: [
            {
              id: 1,
              user: '用户' + Math.floor(Math.random() * 1000),
              rating: Math.floor(Math.random() * 2) + 4,
              time: `${Math.floor(Math.random() * 12) + 1}个月前`,
              content: '师傅手艺很好，解决问题很快，价格也合理，非常满意！'
            },
            {
              id: 2,
              user: '用户' + Math.floor(Math.random() * 1000),
              rating: Math.floor(Math.random() * 2) + 4,
              time: `${Math.floor(Math.random() * 12) + 1}个月前`,
              content: '服务态度很好，准时上门，问题解决得很彻底。'
            }
          ],
          cases: [
            {
              title: '卫生间水管维修案例',
              images: [
                'https://picsum.photos/200/150?random=' + i + 1,
                'https://picsum.photos/200/150?random=' + i + 2
              ],
              description: '解决了卫生间水管漏水问题，更换了老化管道，客户非常满意。'
            },
            {
              title: '墙面修补案例',
              images: [
                'https://picsum.photos/200/150?random=' + i + 3,
                'https://picsum.photos/200/150?random=' + i + 4
              ],
              description: '修补了因潮湿导致的墙面脱落，重新粉刷后焕然一新。'
            }
          ].slice(0, Math.floor(Math.random() * 2) + 1)
        })
      }
      
      masters.value = mockMasters
      totalMasters.value = mockMasters.length
      loading.value = false
    }, 800)
  }
  
  // 根据分类和搜索过滤师傅
  const filteredMasters = computed(() => {
    let result = masters.value
    
    // 按分类过滤
    if (activeCategory.value !== '1') {
      result = result.filter(master => master.categoryId === parseInt(activeCategory.value))
    }
    
    // 按搜索关键词过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      result = result.filter(master => 
        master.name.toLowerCase().includes(query) || 
        master.serviceType.toLowerCase().includes(query) ||
        master.description.toLowerCase().includes(query)
      )
    }
    
    // 分页处理
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return result.slice(start, end)
  })
  
  // 处理分类选择
  const handleCategorySelect = (index) => {
    activeCategory.value = index
    currentPage.value = 1
  }
  
  // 搜索师傅
  const searchMasters = () => {
    currentPage.value = 1
  }
  
  // 分页大小改变
  const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
  }
  
  // 当前页改变
  const handleCurrentChange = (page) => {
    currentPage.value = page
  }
  
  // 显示预约对话框
  const showBookingDialog = (master) => {
    currentMaster.value = master
    bookingForm.value = {
      masterId: master.id,
      masterName: master.name,
      serviceType: master.serviceType,
      bookingTime: '',
      bookingAddress: '',
      problemDescription: ''
    }
    bookingDialogVisible.value = true
  }
  // 提交预约
const submitBooking = () => {
  if (!bookingForm.value.bookingTime) {
    ElMessage.error('请选择预约时间')
    return
  }
  if (!bookingForm.value.bookingAddress) {
    ElMessage.error('请输入服务地址')
    return
  }
  if (!bookingForm.value.problemDescription) {
    ElMessage.error('请输入问题描述')
    return
  }

  // 模拟提交到后端
  loading.value = true
  setTimeout(() => {
    loading.value = false
    bookingDialogVisible.value = false
    ElMessage.success('预约成功！师傅会尽快与您确认')
    // 重置表单
    bookingForm.value = {
      masterId: null,
      masterName: '',
      serviceType: '',
      bookingTime: '',
      bookingAddress: '',
      problemDescription: ''
    }
  }, 1000)
}

// 显示师傅详情
const showDetail = (master) => {
  currentMaster.value = master
  activeTab.value = 'basic'
  detailDialogVisible.value = true
}

// 图片预览
const previewImage = (imgUrl) => {
  // 这里可以使用Element Plus的图片预览组件
  ElMessageBox.alert(`<img src="${imgUrl}" style="max-width: 100%;"/>`, '图片预览', {
    dangerouslyUseHTMLString: true,
    customClass: 'image-preview-modal'
  })
}

// 初始化数据
onMounted(() => {
  initMastersData()
})
</script>

<style scoped>
.repair-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  flex: 1;
}

.main-content {
  display: flex;
  gap: 20px;
}

.category-sidebar {
  width: 200px;
  flex-shrink: 0;
}

.category-menu {
  border-right: none;
}

.master-list-container {
  flex: 1;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  color: var(--el-color-primary);
  gap: 10px;
}

.master-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.master-card {
  margin-bottom: 20px;
}

.master-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.master-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
}

.master-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.master-info {
  flex: 1;
}

.master-name {
  margin: 0 0 5px 0;
  font-size: 18px;
}

.master-tags {
  margin: 5px 0;
}

.master-tags .el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.master-details {
  margin: 15px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: var(--el-text-color-secondary);
}

.detail-item .el-icon {
  margin-right: 8px;
}

.description {
  display: flex;
  align-items: flex-start;
}

.master-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 详情对话框样式 */
.master-detail {
  padding: 10px;
}

.detail-header {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color);
}

.detail-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
}

.detail-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.detail-info h2 {
  margin: 0 0 10px 0;
}

.detail-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.order-count {
  margin-left: 15px;
  color: var(--el-text-color-secondary);
}

.detail-service {
  display: flex;
  gap: 15px;
  color: var(--el-text-color-secondary);
}

.detail-content {
  margin-top: 20px;
}

.basic-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: var(--el-text-color-regular);
}

.description h3 {
  margin: 20px 0 10px 0;
}

.description p {
  margin: 0;
  line-height: 1.6;
}

.review-list {
  margin-top: 15px;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid var(--el-border-color-light);
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.review-user {
  margin-right: 10px;
  font-weight: bold;
}

.review-time {
  margin-left: auto;
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.review-content {
  line-height: 1.5;
}

.case-list {
  margin-top: 15px;
}

.case-item {
  padding: 15px 0;
  border-bottom: 1px solid var(--el-border-color-light);
}

.case-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.case-images {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.case-images img {
  width: 100px;
  height: 75px;
  object-fit: cover;
  cursor: pointer;
  border-radius: 4px;
}

.case-desc {
  line-height: 1.5;
  color: var(--el-text-color-secondary);
}

.no-reviews,
.no-cases {
  text-align: center;
  padding: 30px 0;
  color: var(--el-text-color-secondary);
}

.detail-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .category-sidebar {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .master-list {
    grid-template-columns: 1fr;
  }
  
  .basic-info {
    grid-template-columns: 1fr;
  }
}
</style>